package com.sam.im.sms.reciever;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;

import com.sam.im.greendao.DaoSession;
import com.sam.im.sms.R;
import com.sam.im.sms.app.MyApp;
import com.sam.im.sms.entity.InterceptEntity;
import com.sam.im.sms.setting.SMSSettingImpl;
import com.sam.im.sms.setting.Setting;
import com.sam.im.sms.util.NotificationUtils;
import com.sam.im.sms.util.ToolsUtils;

import java.util.Date;

/**
 * 描述
 * liuyucheng
 * Created By 刘育成 on 2019/5/31.
 */
public class SmsReciever extends BroadcastReceiver {
    private final static String AUTHORITY = "com.android.peter.provider";
    private final static Uri STUDENT_URI = Uri.parse("content://" + AUTHORITY + "/intercept");
    ContentValues contentValues;
    Uri uri;
    NotificationUtils mNotificationUtils;
    private String[] contentProjection = new String[]{PhoneLookup._ID,
            PhoneLookup.DISPLAY_NAME};
    private Setting mSetting;
    private static DaoSession mDaoSession;
    private Context mContext;

    public SmsReciever() {
        mDaoSession = MyApp.getDaoSession();
        mSetting = SMSSettingImpl.getInstance();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context.getApplicationContext();
        mNotificationUtils = new NotificationUtils(context);
        Bundle bundle = intent.getExtras();
        Object[] objects = (Object[]) bundle.get("pdus");
        SmsMessage sms;
        for (Object obj : objects) {
            sms = SmsMessage.createFromPdu((byte[]) obj);
            if (mSetting.isVerify("isVerify")) {
                isIntelligent(sms);
            } else {
                MsgContent(sms, context, 1);
            }
        }
    }

    /**
     * 黑名单
     *
     * @param sms
     */
    private void isBlackList(SmsMessage sms) {
        if (mSetting.isBlackList("blackList")) {
            Log.e("lyc::黑", mSetting.getNumberKeyword("isNumberKeyword"));
            if (ToolsUtils.ListTools(sms.getDisplayOriginatingAddress(), mSetting.getNumberKeyword("isNumberKeyword"))) {
                isWhiteList(sms);
            } else {
                MsgContent(sms, mContext, 2);
            }
        } else {
            Log.e("lyc::规则", ToolsUtils.Tools(mContext, sms) + "");
            //只是开启了骚扰拦截，没有开启拦截规则
            MsgContent(sms, mContext, 4);
        }
    }

    /**
     * 白名单
     *
     * @param sms
     */
    private void isWhiteList(SmsMessage sms) {
        Log.e("lyc::白", mSetting.getWNumberKeyword("isWNumberKeyword"));
        if (ToolsUtils.ListTools(sms.getOriginatingAddress(), mSetting.getWNumberKeyword("isWNumberKeyword"))) {
            Log.e("lyc:白名单", "在白名单中");
            MsgContent(sms, mContext, 3);
        } else {
            Log.e("lyc", "不在白名单中");
            isRemind(sms);
        }
    }

    /**
     * 智能拦截
     *
     * @param sms
     */
    private void isIntelligent(SmsMessage sms) {
        if (mSetting.isIntelligent("intelligent")) {
            if (ToolsUtils.Tools(mContext, sms)) {
                isRemind(sms);
            } else {
                isBlackList(sms);
            }
        } else {
            isBlackList(sms);
        }
    }

    private void isRemind(SmsMessage sms) {
        if (mSetting.isRemind("isRemind")) {
            mNotificationUtils.sendSMSNotification("自动为您拦截一条垃圾信息");
            abortBroadcast();
        } else {
            abortBroadcast();
        }
        contentValues=new ContentValues();
        contentValues.put("address", sms.getDisplayOriginatingAddress());
        contentValues.put("type", "1");
        contentValues.put("read", "0");
        contentValues.put("body", sms.getDisplayMessageBody());
        contentValues.put("date", new Date().getTime());
        mContext.getApplicationContext().getContentResolver().insert(STUDENT_URI, contentValues);
    }


    private void MsgContent(SmsMessage sms, Context context, int x) {
        Log.e("lyc", x + "");
        /**
         * 定义成局部变量，不要定义成成员变量
         */
        String phoneName = null;
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(sms.getDisplayOriginatingAddress()));
        Cursor concatCursor = context.getContentResolver().query(uri,
                contentProjection, null, null, null);
        if (concatCursor.moveToFirst()) {
            // 查询到了联系人
            phoneName = concatCursor.getString(1);
        }

        if (phoneName != null) {
            mNotificationUtils.sendNotification(context, phoneName, sms.getDisplayMessageBody(), sms.getDisplayOriginatingAddress());
        } else {
            mNotificationUtils.sendNotification(context, sms.getDisplayOriginatingAddress(), sms.getDisplayMessageBody(), sms.getDisplayOriginatingAddress());
        }
        contentValues = new ContentValues();
        contentValues.put("address", sms.getDisplayOriginatingAddress());
        contentValues.put("type", "1");
        contentValues.put("read", "0");
        contentValues.put("body", sms.getDisplayMessageBody());
        contentValues.put("date", new Date().getTime());
        context.getApplicationContext().getContentResolver().insert(Uri.parse("content://sms/inbox"), contentValues);
    }
}
